package com.serkol.driving.learning.api;


import com.serkol.bean.Result;
import com.serkol.driving.learning.entity.LoginLog;
import com.serkol.driving.learning.entity.Menu;
import com.serkol.driving.learning.service.MenuService;
import com.serkol.annotation.IsLogin;
import com.serkol.constant.AuthConstant;
import com.serkol.constant.ResultConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("api/oauth/menu")
public class MenuApiController {

    @Autowired
    private MenuService menuService;

    @IsLogin
    @GetMapping("/list")
    public Result list() {
        Result result = new Result();
        LoginLog loginLog = AuthConstant.getLoginLog();
        List<Map<String, Object>> list = menuService.fetchMenuList(loginLog.getRoleId());
        if (!list.isEmpty()) {
            result.setStatus(ResultConstant.SUCSESS);

            result.setData(list);
        } else {
            result.setStatus(ResultConstant.EMPTIY);
        }

        return result;
    }

    @IsLogin
    @PostMapping("/edit")
    public Result edit(@RequestBody Menu menu) {
        menu.setParentId(menu.getParentId() != null && menu.getParentId() != 0 ? menu.getParentId() : null);
        boolean flag = false;
        if (menu.getId() != null && menu.getId() > 0) {
            flag = menuService.updateById(menu);
        } else {
            flag = menuService.save(menu);
        }
        if (flag) {
            return Result.ok();
        } else {
            return Result.failure();
        }

    }

    @IsLogin
    @GetMapping("/listTree")
    public Result listTree() {
        Result result = new Result();
        List<Map<String, Object>> list = menuService.fetchMenuTreeList();
        if (!list.isEmpty()) {

            result.setStatus(ResultConstant.SUCSESS);

            result.setData(list);
        } else {
            result.setStatus(ResultConstant.EMPTIY);
        }

        return result;
    }

    @IsLogin
    @GetMapping("/listSelect")
    public Result listSelect() {
        Result result = new Result();
        List<Map<String, Object>> list = menuService.listSelect();
        if (!list.isEmpty()) {

            result.setStatus(ResultConstant.SUCSESS);

            result.setData(list);
        } else {
            result.setStatus(ResultConstant.EMPTIY);
        }

        return result;
    }
}
